var uploadProgressRefresherTask;

Ext.define('WebMeV.controller.FileUpload', {
    extend : 'Ext.app.Controller',

    //define the views
    views : ['UploadForm'],

    //special method that is called when your application boots
    init : function() {
              
        //control function makes it easy to listen to events on
        //your view classes and take some action with a handler function
        this.control({
                  
//            //when the viewport is rendered
//            'viewport > panel' : {
//                render : this.onPanelRendered
//            },
            //when you click Upload file button
            'fileuploadform button[action=uploadFile]' : {
                click : this.uploadFile  
            },
            'fileuploadform button[action=resetForm]' : {
                click : this.clearForm  
            }
        });
    },

    onPanelRendered : function() {
        //just a console log to show when the panel is rendered
        console.log('The panel was rendered');
    },
          
    displayMessage : function(title, format){
        var msgCt;
        if(!msgCt){
            msgCt = Ext.core.DomHelper.insertFirst(document.body, {
                id:'msg-div'
            }, true);
        }
        var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
        var m = Ext.core.DomHelper.append(msgCt, this.createBox(title, s), true);
        m.hide();
        m.slideIn('t').ghost("t", {
            delay: 2000, 
            remove: true
        });
    },
          
    createBox : function (t, s){
        return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';
    },
    
    clearFileUpload: function (id){
        // get the file upload element
        var fileField     = document.getElementById(id);
        // get the file upload parent element
        var parentNod     = fileField.parentNode;
        // create new element
        var tmpForm        = document.createElement("form");
        parentNod.replaceChild(tmpForm,fileField);
        tmpForm.appendChild(fileField);
        tmpForm.reset();
        parentNod.replaceChild(fileField,tmpForm);
    },
    
    clearForm : function(button) {
        console.log('Reset Upload Form');
        this.clearFileUpload("myFile");
    },
    
    doAjax : function () {
        Ext.Ajax.request({
            url: 'fileupload',
            method: 'GET',
            success: function ( result, request) {
                var jsonData = Ext.decode(result.responseText);
                var pr = jsonData.count/100;
                
                if(Math.round(pr*100)){
                    if(Ext.getCmp('prgb'))
                        if(Math.round(pr*100) == 100)
                            Ext.getCmp('prgb').updateProgress(pr,'Done');
                        else
                            Ext.getCmp('prgb').updateProgress(pr, "Uploading your file...&nbsp;"+Math.round(pr*100)+"%", true);
                }
            },
            failure: function ( result, request) {
                Ext.MessageBox.alert('Failed', 'Failed');
            }
        });
    },   

    uploadFile : function(button) {
        //just a console log to show when the file Upload starts
       //console.log('File Upload in progress');
                              
        var form = button.up('form').getForm();
        if(form.isValid()){

            Ext.getCmp('prgb').show();
            Ext.getCmp("fl").setVisible(false);
            
            uploadProgressRefresherTask = {
                run: this.doAjax,
                interval: 500,
                repeat: 5000
            }
            
            Ext.TaskManager.start(uploadProgressRefresherTask);
            
            form.submit({
                url: 'fileupload',
                scope: this,
                success: function(form, action){
                    this.clearFileUpload("myFile");

                    // server responded with success = true
                    var restext = action.response.responseText;
                    response = Ext.decode(restext);
                    if(response.success){
                        Ext.TaskManager.stop(uploadProgressRefresherTask);
                        Ext.getCmp('prgb').updateProgress(0,"");
                        Ext.getCmp('prgb').hide();
                        if(!start){
                            Ext.getCmp('ns').enable();
                            this.displayMessage('File Uploaded Successfully', 'Ready for analysis... click on ""New Start"');                       
                        }
                        else {
                            //TODO 
                            //start first here without needs to click on the "New Start" button
                            this.startHeatMap(response.file);
                            start = false;
                        }
                    }
                },
                failure: function(form, action){
                    if (action.failureType === CONNECT_FAILURE) {
                        Ext.Msg.alert('Error', 'Status:'+action.response.status+': '+
                            action.response.statusText);
                    }
                    if (action.failureType === SERVER_INVALID){
                        // server responded with success = false
                        Ext.Msg.alert('Invalid', action.result.errormsg);
                    }
                }
            });
        }
    },
    
    startHeatMap: function(fileName){
        var url = 'analysis?file='+fileName+'&action=heatmap';
        Ext.Ajax.request({
            url: url,
            method: 'GET',
            success: function ( result, request) {
                Ext.MessageBox.alert('Success', result.responseText);
                var jsonData = Ext.decode(result.responseText);                
            },
            failure: function ( result, request) {
                Ext.MessageBox.alert('Failed', 'Failed');
            }
        });
    }
      
});